// 子组件 修改与添加共用弹框
import React, { useEffect, useState } from 'react'
import {
  Button,
  Upload,
  Modal,
  message,
  Form,
  Input,
  Space,
  Switch,
  Select,
} from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import type { UploadChangeParam } from 'antd/es/upload'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { chabgeDiy } from '../../../../api/finance'
import '../../../css/AddorRev.css'
//
interface PropsType {
  modalClose(): void
  isModalOpen: boolean
  head: string | null
  redactList: {}
}

const { TextArea } = Input
export default function ClassChild(props: any) {
  const [redactList, setRedactList] = useState<any>()
  useEffect(() => {
    console.log('redactList=======>', props.redactList)
    setRedactList(props.redactList)
  }, [props])

  // 对话框部分
  const handleOk = () => {
    props.modalClose()
  }

  const handleCancel = () => {
    props.modalClose()
  }
  // 表单部分
  const onFinish = (values: any) => {
    console.log('Success:', values)
    chabgeDiy({
      "categoryId": redactList.categoryId,
      "categoryName": `${values.title}`
    }).then((res) => {
      console.log('res编辑====>', res);
      props.getList()
    }).catch((err) => {
      console.log('err编辑====>', err);
    });
    props.modalClose()
    message.success('提交成功！')
  }

  // 开关按钮
  const onChangeSwitch = (checked: boolean) => {
    console.log(`switch to ${checked}`)
  }

  // 头像部分
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result as string))
    reader.readAsDataURL(img)
  }

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!')
    }
    return isJpgOrPng && isLt2M
  }

  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState<string>()

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false)
        setImageUrl(url)
      })
    }
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  )

  const onChange2 = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    console.log('Change:', e.target.value)
  }

  const handleChange2 = () => {
    console.log();

  }
  return (
    <>
      <Modal
        title={props.head}
        open={props.isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          {/* 标题 */}
          <Form.Item
            label="分类名称"
            name="title"
            initialValue={redactList?.type}
          >
            <Input />
          </Form.Item>

          {/* 上级分类 */}
          <Form.Item
            label="上级分类"
            name="state"
          >
            <Space wrap>
              <Select
                onChange={handleChange2}
                style={{ width: 120 }}
                allowClear
                options={[
                  { value: '一级', label: '一级' },
                  { value: '二级', label: '二级' },
                  { value: '三级', label: '三级' },
                ]}
                className="drop"
              />
            </Space>
          </Form.Item>
          {/* 排序 */}
          <Form.Item
            label="排序"
            name="location"
            initialValue={props.redactList?.key}
          >
            <Input />
          </Form.Item>
          {/* 是否上架开关 */}
          <Form.Item name="switch" label="上架">
            <Switch defaultChecked onChange={onChangeSwitch} />
          </Form.Item>
          {/* 图片 */}
          <Form.Item
            label="封面图片"
            name="photo"
            valuePropName="fileList" /* 子节点的值的属性 */
            getValueFromEvent={(e) => {
              /* 设置如何将 event 的值转换成字段值 */
              if (Array.isArray(e)) {
                return e
              }
              return e && e.fileList
            }}
          >
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item label="分类描述">
            <TextArea
              showCount
              maxLength={100}
              style={{ height: 120, resize: 'none' }}
              onChange={onChange2}
              placeholder="此分类为{}专用商品"
            />
          </Form.Item>

          {/* 操作按钮 */}
          <Form.Item wrapperCol={{ offset: 8, span: 16 }} className="opreate">
            <Button type="primary" htmlType="submit" className="submit">
              提交
            </Button>
            <Button type="primary" onClick={handleCancel} className="cancel">
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
